const config = require("../config/config");
const COS = require('../libs/cos-wx-sdk-v5.min');
const {
  AuthService
} = require("../services/auth_service");


// const uploadImage = async (filePath) => {
//   const token = wx.getStorageSync('token');
//   return new Promise((resolve, reject) => {
//     wx.uploadFile({
//       filePath: filePath,
//       name: 'name',
//       url: `${config.baseUrl}/photo/upload`,
//       header: {
//         Authorization: token
//       },
//       success: (res) => {
//         resolve(JSON.parse(res.data))
//       },
//       fail: (error) => {
//         reject(error);
//       }
//     })
//   })
// }

const cos = new COS({
  getAuthorization: function (options, callback) {
    // 服务端 JS 和 PHP 示例：https://github.com/tencentyun/cos-js-sdk-v5/blob/master/server/
    // 服务端其他语言参考 COS STS SDK ：https://github.com/tencentyun/qcloud-cos-sts-sdk
    // STS 详细文档指引看：https://cloud.tencent.com/document/product/436/14048

    let authService = new AuthService();
    authService.getCosTempKey().then(res => {
      var data = res.data;
      var credentials = data && data.credentials;
      console.log(credentials);
      console.log(data);
      if (!data || !credentials) return console.error('credentials invalid');
      callback({
        TmpSecretId: credentials.tmpSecretId,
        TmpSecretKey: credentials.tmpSecretKey,
        XCosSecurityToken: credentials.sessionToken,
        // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
        StartTime: data.startTime, // 时间戳，单位秒，如：1580000000
        ExpiredTime: data.expiredTime, // 时间戳，单位秒，如：1580000900
      });
    })
  }
});

const uploadFile = async (filePath) => {
  var fileName = filePath.substring(filePath.lastIndexOf('/') + 1);
  const userId = getApp().globalData.userInfo.id;
  return new Promise((resolve, reject) => {
    cos.postObject({
      Bucket: 'photo-1310140047',
      Region: 'ap-guangzhou',
      Key: 'users/' + userId + '/' + fileName,
      FilePath: filePath
    }, (error, data) => {
      if (error) {
        reject(error);
      }
      let url = 'https://static.fishto.cn/' + data.Location.substring(data.Location.indexOf('/') + 1);
      resolve(url);
    })
  });
}



module.exports = uploadFile;